<template>
  <div style="height: 100%">
    <div class="formCard-content">
      <Card :bordered="false" :dis-hover="true" :shadow="false" class="formCard">
        <div class="searchArea" >
          <Form ref="queryForm" :model="queryForm" :label-width="80" >
            <Row :gutter="40">
              <Col span="8" style="margin-bottom: 12px">
                <FormItem label="链接名称"  prop="urlName" style="width: 100%">
                  <Input  type="text" :maxlength="100" v-model.trim="queryForm.urlName" placeholder="请输入链接名称" style="width: 100%"></Input>
                </FormItem>
            </Col>
              <Col span="8" style="margin-bottom: 12px">
                <FormItem label="分类"  prop="type" style="width: 100%">
                  <Select v-model="queryForm.type" placeholder="请选择">
                    <Option v-for="item in typeDicGroups" :value="item.itemCode.toLocaleString()"
                            :key="item.itemCode.toLocaleString()">{{ item.itemValue }}
                    </Option>
                  </Select>
                </FormItem>
            </Col>
              <Col span="8" style="margin-bottom: 12px">
                <FormItem label="系统"  prop="system" style="width: 100%">
                  <Select v-model="queryForm.system" placeholder="请选择">
                    <Option v-for="item in systemDicGroups" :value="item.itemCode.toLocaleString()"
                            :key="item.itemCode.toLocaleString()">{{ item.itemValue }}
                    </Option>
                  </Select>
                </FormItem>
            </Col>
              <Col span="24" style="text-align: right;margin-top: 12px">
                <FormItem :label-width="0">
                  <Button   type="primary" @click="queryList(true)" style="margin-right: 8px">查询</Button>
                  <Button type="default"  @click="handleReset('queryForm')">重置</Button>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </div>
      </Card>
      <Card :bordered="false" :dis-hover="true" :shadow="false" class="formCard">
        <div class="tableBtn">
          <Button  icon="md-add"  type="primary"  @click="handleAdd()">新增</Button>
          <Button  icon="ios-trash-outline" type="error"  @click="handleDeleteMultiple()" style="margin-left: 20px">删除</Button>
        </div>
        <Table  :columns="columns" :data="data" @on-selection-change="rowSelected($event)" style="">
          <template slot-scope="{ row, index }" slot="action">
            <Button type="text" size="small"  style="margin-right: 5px;color: #0056B5" @click="handleEdit(row,index)">编辑</Button>
            <Button  type="text" size="small" style="margin-right: 5px;color: #0056B5" @click="remove(row, index)">删除</Button>
          </template>
        </Table>
        <Page :total="pageData.total" :page-size="pageData.size" :current="pageData.page" show-elevator show-sizer show-total @on-page-size-change="changePage($event, 'size')" @on-change="changePage($event, 'page')" style="margin-top: 20px;"/>
      </Card>
    </div>
    <Modal
      v-model="modal"
      :title="title"
      ref="modal"
      @on-cancel="close"
      :width="580"
    >
      <Form ref="detail" :model="detail" :label-width="80" :rules="ruleValidate" style="margin-top: 20px">
        <FormItem label="链接名称"  prop="urlName">
            <Input type="text" :maxlength="100" v-model.trim="detail.urlName" placeholder="请输入链接名称" ></Input>
        </FormItem>
        <FormItem label="链接logo"  prop="urlLogo" class="upload-form-img">
          <Button type="primary" style="width:150px" @click="uploadCover">选择图片</Button>
          <span class="img-notice">要求：可上传jpg png gif图片 大小要求小于300k</span>
          <div class="img-wrapper">
            <div>
              <div class="add-img">
              <span style="filter: opacity(0.5)">
                <Icon type="ios-add-circle" size='40' />
              </span>
<!--                todo-->
                <input ref="coverImage" type="file" accept="image/*" @change="imgChange" >
              </div>
              <p style="text-align:center">可上传图片</p>
            </div>
            <div v-if="detail.urlLogo != '' && detail.urlLogo != null && detail.urlLogo != undefined">
              <div class="add-img" style="position:relative" >
<!--                <img :src="`http://localhost:28080/upload-pic/${detail.urlLogo}`">-->
                <img :src="this.$util.baseUrl + '/upload-pic/' + detail.urlLogo">
<!--                <Icon class="close-icon" type="md-close-circle" size='26' />-->
              </div>
<!--              <p style="text-align:center">{{detail.cover.file != null ? detail.cover.file.name : ''}}</p>-->
            </div>
          </div>
        </FormItem>
        <FormItem label="链接地址"  prop="urlPath">
            <Input type="text" :maxlength="100" v-model.trim="detail.urlPath" placeholder="请输入链接地址" ></Input>
        </FormItem>
        <FormItem label="分类"  prop="type">
            <Select v-model="detail.type" placeholder="请选择分类" clearable >
              <Option v-for="item in typeDicGroups" :value="item.itemCode.toLocaleString()"
                    :key="item.itemCode.toLocaleString()">{{ item.itemValue }}
              </Option>
            </Select>
        </FormItem>

        <FormItem label="系统"  prop="system">
            <Select v-model="detail.system" placeholder="请选择系统" clearable >
              <Option v-for="item in systemDicGroups" :value="item.itemCode.toLocaleString()"
                    :key="item.itemCode.toLocaleString()">{{ item.itemValue }}
              </Option>
            </Select>
        </FormItem>

        <FormItem label="部门"  prop="dept">
            <Input type="text" :maxlength="100" v-model.trim="detail.dept" placeholder="请输入部门" ></Input>
        </FormItem>
       <FormItem label="是否内网"  prop="privateNetworkFlag">
          <RadioGroup v-model="detail.privateNetworkFlag">
             <Radio v-for="item in privateNetworkFlagDicGroups" :label="item.itemCode.toLocaleString()" :key="item.itemCode.toLocaleString()">
                 <span>{{item.itemValue}}</span>
             </Radio>
          </RadioGroup>
       </FormItem>
       <FormItem label="是否互通"  prop="connectFlag">
          <RadioGroup v-model="detail.connectFlag">
             <Radio v-for="item in connectFlagDicGroups" :label="item.itemCode.toLocaleString()" :key="item.itemCode.toLocaleString()">
                 <span>{{item.itemValue}}</span>
             </Radio>
          </RadioGroup>
       </FormItem>
      </Form>
      <div slot="footer">
        <Button type="primary"  @click="ok(okFlag)" :disabled="disabled"  style="width: 80px">确定</Button>
        <Button type="default"  @click="close()"  style="width: 80px">取消</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
export default {
  name: 'urlManagementManager',
  data () {
     const validatetype = (rule, value, callback) => {
         if (!value) {
             callback(new Error('请输入分类！'))
             return
         }
         callback()
     }
     const validatesystem = (rule, value, callback) => {
         if (!value) {
             callback(new Error('请输入系统！'))
             return
         }
         callback()
     }
     const validateprivateNetworkFlag = (rule, value, callback) => {
         if (!value) {
             callback(new Error('请输入是否内网！'))
             return
         }
         callback()
     }
     const validateconnectFlag = (rule, value, callback) => {
         if (!value) {
             callback(new Error('请输入是否互通！'))
             return
         }
         callback()
     }
    return {
      typeDicGroups: [],
      systemDicGroups: [],
      privateNetworkFlagDicGroups: [],
      connectFlagDicGroups: [],
      modal: false,
      disabled: false,
      selectedArr: [],
      queryForm: {},
      pageData: {
        total: 0,
        size: 10,
        page: 1
      },
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          type: 'index',
          align: 'center',
          title: '序号',
          width: 80
        },
        {
          title: '链接名称',
          key: 'urlName'
        },
        {
          title: '链接地址',
          key: 'urlPath'
        },
        {
          title: '分类',
          key: 'type',
          render: (h, params) => {
            return h('span', this.typeTranslate(params.row))
          }
        },
        {
          title: '系统',
          key: 'system',
          render: (h, params) => {
            return h('span', this.systemTranslate(params.row))
          }
        },
        {
          title: '部门',
          key: 'dept'
        },
        {
          title: '操作',
          slot: 'action',
          width: 300,
          align: 'center'
        }
      ],
      data: [
      ],
      detail: {
        cover: {
          file: null,
          url: '',
          name: ''
        },
        urlLogo: ''
      },
      okFlag: '',
      modalValid: true,
      ruleValidate: {
        'type': [
            { required: true, validator: validatetype, trigger: 'blur' }
         ],
        'system': [
            { required: true, validator: validatesystem, trigger: 'blur' }
         ],
        'privateNetworkFlag': [
            { required: true, validator: validateprivateNetworkFlag, trigger: 'blur' }
         ],
        'connectFlag': [
            { required: true, validator: validateconnectFlag, trigger: 'blur' }
         ],
      }
    }
  },
  mounted () {
    this.queryList()
    this.typeGetDicGroups('urlType')
    this.systemGetDicGroups('system')
    this.privateNetworkFlagGetDicGroups('privateNetwork')
    this.connectFlagGetDicGroups('connect')
  },
  computed: {
    title: function () {
      if (this.okFlag === 'add') {
        return '新增'
      } else {
        return '编辑'
      }
    }
  },
  methods: {
    uploadCover () {
      this.$refs.coverImage.click()
    },
    imgChange () {
      let file = this.$refs.coverImage.files[0]
      let fileName = file.name
      let fileType = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase()
      if (fileType !== 'png' && fileType !== 'jpg' && fileType !== 'gif') {
        this.$Message.error('上传图片格式不正确')
        return
      }
      // 可以对文件大小进行限制
      if (file.size > 300 * 1024) {
        this.$Message.error('图片大小应在300k以下')
        return
      }
      // this.detail.cover.file = file
      // this.detail.cover.name = fileName
      // 读取文件
      // this.detail.cover.url = this.toBlobURL(file)

      // 上传图片
      this.handleUpload(file);
    },
    handleUpload(file) {
      let this_ = this;
      let formData = new FormData();
      formData.append("file", file);
      const url = `api/urlManagement/uploadPicture`;
      this.$http.post(url, formData).then((res) => {
        if (res.data.code == 200) {
          this.$message.success("上传成功");
          this_.detail.urlLogo =  res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    toBlobURL (blob) {
      return window[window.webkitURL ? 'webkitURL' : 'URL']['createObjectURL'](blob)
    },
    typeGetDicGroups(urlType){
         const [url, httpConfig] = [
            '/api/dic/cscpHxDicItems/getCscpBasicHxItemCode',
            {
              params: {
                // 'dicAttr.equals' : 'list',
                'dicCode' : 'urlType'
              }
            }
         ]
         this.$http.get(url, httpConfig).then(response => {
            this.typeDicGroups = response.data.data
         })
    },
    typeTranslate(row) {
      if(!row.type){
        return row.type
      }
      let realGroupName
      for (let i = 0; i < this.typeDicGroups.length; i++) {
        if (row.type.toLocaleString() === this.typeDicGroups[i].itemCode.toLocaleString()) {
            realGroupName = this.typeDicGroups[i].itemValue.toLocaleString()
        }
      }
      if(realGroupName){
        return realGroupName
      }else{
        return row.type
      }
    },
    systemGetDicGroups(system){
         const [url, httpConfig] = [
            '/api/dic/cscpHxDicItems/getCscpBasicHxItemCode',
            {
              params: {
                // 'dicAttr.equals' : 'list',
                'dicCode' : 'system'
              }
            }
         ]
         this.$http.get(url, httpConfig).then(response => {
            this.systemDicGroups = response.data.data
         })
    },
    systemTranslate(row) {
      if(!row.system){
        return row.system
      }
      let realGroupName
      for (let i = 0; i < this.systemDicGroups.length; i++) {
        if (row.system.toLocaleString() === this.systemDicGroups[i].itemCode.toLocaleString()) {
            realGroupName = this.systemDicGroups[i].itemValue.toLocaleString()
        }
      }
      if(realGroupName){
        return realGroupName
      }else{
        return row.system
      }
    },
    privateNetworkFlagGetDicGroups(privateNetwork){
         const [url, httpConfig] = [
            '/api/dic/cscpHxDicItems/getCscpBasicHxItemCode',
            {
              params: {
                // 'dicAttr.equals' : 'list',
                'dicCode' : 'privateNetwork'
              }
            }
         ]
         this.$http.get(url, httpConfig).then(response => {
            this.privateNetworkFlagDicGroups = response.data.data
         })
    },
    privateNetworkFlagTranslate(row) {
      if(!row.privateNetworkFlag){
        return row.privateNetworkFlag
      }
      let realGroupName
      for (let i = 0; i < this.privateNetworkFlagDicGroups.length; i++) {
        if (row.privateNetworkFlag.toLocaleString() === this.privateNetworkFlagDicGroups[i].itemCode.toLocaleString()) {
            realGroupName = this.privateNetworkFlagDicGroups[i].itemValue.toLocaleString()
        }
      }
      if(realGroupName){
        return realGroupName
      }else{
        return row.privateNetworkFlag
      }
    },
    connectFlagGetDicGroups(connect){
         const [url, httpConfig] = [
            '/api/dic/cscpHxDicItems/getCscpBasicHxItemCode',
            {
              params: {
                // 'dicAttr.equals' : 'list',
                'dicCode' : 'connect'
              }
            }
         ]
         this.$http.get(url, httpConfig).then(response => {
            this.connectFlagDicGroups = response.data.data
         })
    },
    connectFlagTranslate(row) {
      if(!row.connectFlag){
        return row.connectFlag
      }
      let realGroupName
      for (let i = 0; i < this.connectFlagDicGroups.length; i++) {
        if (row.connectFlag.toLocaleString() === this.connectFlagDicGroups[i].itemCode.toLocaleString()) {
            realGroupName = this.connectFlagDicGroups[i].itemValue.toLocaleString()
        }
      }
      if(realGroupName){
        return realGroupName
      }else{
        return row.connectFlag
      }
    },
    close () {
      this.modal = false
      this.$refs['detail'].resetFields()
      this.disabled = false
    },
    changePage (e, type) {
      if (type === 'size') {
        this.pageData.size = e
      } else if (type === 'page') {
        this.pageData.page = e
      }
      this.queryList()
    },
    handleAdd () {
      // this.detail = {
      //   cover: {
      //     file: null,
      //     url: '',
      //     name: ''
      //   },
      //   urlLogo: ''
      // }
      console.log("add start")
      console.log(this.detail)
      console.log("add end")
      this.okFlag = 'add'
      this.modal = true
    },
    handleEdit (row, index) {
       this.$http.get('/api/urlManagements/' + row.id).then(res => {
       this.modal = true
       this.detail = res.data.data
        if(res.data.data.type){
            this.detail.type = res.data.data.type.toLocaleString()
        }
        if(res.data.data.system){
            this.detail.system = res.data.data.system.toLocaleString()
        }
        if(res.data.data.privateNetworkFlag){
            this.detail.privateNetworkFlag = res.data.data.privateNetworkFlag.toLocaleString()
        }
        if(res.data.data.connectFlag){
            this.detail.connectFlag = res.data.data.connectFlag.toLocaleString()
        }
         console.log("edit start")
         console.log(this.detail)
         console.log("edit end")
       this.okFlag = 'update'
       }).catch(() => {
        this.$Message.error('行数据查询失败')
       })
    },
    handleReset (name) {
      this.$refs[name].resetFields()
      this.selectedArr = []
      this.queryList()
    },
    rowSelected (e) {
      this.selectedArr = e
    },
    remove (row, index) {
      this.$Modal.confirm({
        title: '警告',
        content: '<p>确定删除这条数据？</p>',
        onOk: () => {
        this.$http.delete('/api/urlManagements/' + row.id).then(res => {
            if (res.data.msg) {
            this.$Message.error(res.data.msg)
            return
            } else this.$Message.success('删除成功')
            this.queryList()
            }).catch(() => {
            this.$Message.error('删除失败')
            })
        },
        onCancel: () => {}
        })
    },
    ok (type) {
      this.$delete(this.detail, '')
      this.$delete(this.detail, '_rowKey')
      let copyDetail = JSON.parse(JSON.stringify(this.detail))

      this.$refs['detail'].validate((valid) => {
        if (valid) {
            if (type === 'update') {
                this.$http.put('/api/urlManagements', copyDetail).then(res => {
                this.$Message.success('修改成功')
                this.modal = false
                this.queryList()
                this.$refs['detail'].resetFields()
                }).catch(() => {
                this.$Message.error('修改失败')
                })
            } else if (type === 'add') {
                this.$http.post('/api/urlManagements', copyDetail).then(res => {
                this.$Message.success('新增成功')
                this.modal = false
                this.$refs['queryForm'].resetFields()
                this.queryList()
                this.$refs['detail'].resetFields()
                  console.log(this.detail)
                }).catch(() => {
                this.$Message.error('新增失败')
                })
            }
        } else {
            this.modal = true
        }
        })
    },
    queryList (flag) {
      if (flag) {
        this.pageData.page = 1
      }
      let obj = {}
      obj['urlName'] = this.queryForm['urlName']  ?  this.queryForm['urlName']: null
      obj['type'] = this.queryForm['type']  ?  this.queryForm['type']: null
      obj['system'] = this.queryForm['system']  ?  this.queryForm['system']: null
      let params = Object.assign(obj, {
        page: this.pageData.page,
        size: this.pageData.size,
      })
      this.$http.get('/api/urlManagements/', {
        params: params
        }).then(res => {
            this.data = res.data.list
            this.pageData.total = res.data.total
        }).catch(() => {
        this.$Message.error('列表查询失败')
        })
    },
    handleDeleteMultiple: function () {
      let arr = this.selectedArr.map(item => item.id)
      if (arr.length < 1) {
        return this.$Message.error('删除失败,当前选择列表为空！')
      }
      this.$Modal.confirm({
        title: '警告',
        content: '<p>确定删除勾选的数据？</p>',
        onOk: () => {
        this.$http.delete('/api/urlManagements/delAll?ids=' + arr).then(res => {
            this.$Message.success('删除成功')
            this.queryList()
            }).catch(error => {
            if (error.response) {
            this.$Message.error(error.response.data.title ? error.response.data.title : '删除失败！')
            }
            })
        },
        onCancel: () => {
        }
      })
    }
  }
 }
</script>

<style lang="less" scoped>
   @import "~@/views/admin/styles/formStyle.less";
   // 上传图片样式示例
   .upload-form-img{
     .img-notice{
       margin-left: 50px;
       color: #ed4014;
       font-size: 14px;
       line-height: 1;
       padding: 10px 12px 10px 0;
       box-sizing: border-box;
     }
     .img-wrapper {
       display: flex;
       .add-img {
         margin-top: 10px;
         width: 180px;
         height: 130px;
         border: 1px dashed #dcdee2;
         border-radius: 4px;
         cursor: pointer;
         position: relative;
         margin-right: 10px;
         .close-icon {
           position:absolute;
           filter: opacity(0.7);
           right:-13px;
           top:-13px;
         }
         img {
           width: 100%;
           height: 100%;
         }
         span {
           position: absolute;
           top: 50%;
           left: 50%;
           transform: translate(-50%, -50%);
           z-index: 1;
         }
         input {
           position: relative;
           z-index: 10;
           width: 100%;
           height: 100%;
           opacity: 0;
           cursor: pointer;
         }
       }
     }
   }
</style>
